
import path from "path"
import fs from "fs"

/** @type {import('vite').Plugin} */
export default {
    name: 'view-html-plugin',
    configureServer(server) {
        server.middlewares.use((req, res, next) => {
            let url = req.url;

            if (url === "/") url = "/workbench.html"

            // 检查请求路径是否以 .html 结尾
            if (url.includes('.html')) {

                // 指定返回文件的路径, 注意替换为你的实际文件路径
                const filePath = path.resolve(__dirname, '../../view.html');
                const [vuePath] = url.split(".html")

                let scriptSrc = `/deliver-center-view/src/views/deliver-center${vuePath}/main.js`

                if (vuePath.startsWith("/demo")) {
                    scriptSrc = `/deliver-center-view/src/views/_common${vuePath}/main.js`
                }

                // 读取并返回文件内容
                fs.readFile(filePath, 'utf-8', (err, html) => {
                    html = html.replace("__VUE_PATH__", scriptSrc)

                    if (err) {
                        res.statusCode = 500;
                        res.end('Internal Server Error');
                    } else {
                        res.setHeader('Content-Type', 'text/html');
                        res.end(html);
                    }
                });
            } else {
                // 非 .html 结尾的请求，交由后续中间件处理
                next();
            }
        });
    },
}